
package com.zch.starter.opentelemetry.agent.mode.springboot.starter.utils;

import io.opentelemetry.api.baggage.Baggage;
import io.opentelemetry.api.baggage.BaggageBuilder;
import io.opentelemetry.api.trace.*;
import io.opentelemetry.sdk.trace.IdGenerator;

import java.util.Objects;


public class TraceUtils {

/**
     * 获取traceId
     */

    public static String getTraceId() {

        String traceId = "";
        Span currentSpan = Span.current();
        if (Objects.nonNull(currentSpan)) {
            SpanContext spanContext = currentSpan.getSpanContext();
            if (Objects.nonNull(spanContext)) {
                traceId = spanContext.getTraceId();
            }
        }
        return traceId;
    }


/**
     * 获取Span
     */

    public static String getSpanId() {
        String spanId = "";
        Span currentSpan = Span.current();
        if (Objects.nonNull(currentSpan)) {
            SpanContext spanContext = currentSpan.getSpanContext();
            if (Objects.nonNull(spanContext)) {
                spanId = spanContext.getSpanId();
            }
        }
        return spanId;
    }


    /**
     * 创建服务标准的traceId
     * @return
     */
    public static String createTraceId() {
        String traceId = IdGenerator.random().generateTraceId();
        return traceId;
    }

    /**
     * 检验是否符合
     * @param traceId
     * @return
     */
    public static boolean isValidTraceId(String traceId) {
        return TraceId.isValid(traceId);
    }


    /**
     * 检验是否符合
     * @param spanId
     * @return
     */
    public static boolean isValidSpanId(String spanId) {
        return SpanId.isValid(spanId);
    }



    /**
     * 主动创建spanid
     * @return
     */
    public static String createSpanId() {
        String spanId = IdGenerator.random().generateSpanId();
        return spanId;
    }

    /**
     * 1 Baggage 是 OpenTelemetry 中用来存储传递业务额外参数的-键值对存储机制，非MDC!
     * 2 Baggage是存储在OpenTelemetry 的Context 中的键值对，非MDC!
     * @param key
     * @param value
     */
    public static void putToBaggage(String key, String value) {
        Baggage current = Baggage.current();
        BaggageBuilder builder = current.toBuilder();
        builder.put(key, value);
        builder.build().makeCurrent();
    }

    /**
     * 1 Baggage 是 OpenTelemetry 中用来存储传递业务额外参数的-键值对存储机制，非MDC!
     * 2 Baggage是存储在OpenTelemetry 的Context 中的键值对，非MDC!
     * @param key
     * @return
     */
    public static String getFromBaggage(String key) {
        return Baggage.current().getEntryValue(key);
    }

}

